﻿using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Channels;

namespace RFServer.ServiceWCF
{
    [ServiceContract(Namespace="RFService", Name="RFServer")]
    interface IMainService
    {
        [OperationContract]
        string[] Select(string[] keywords);

        [OperationContract]
        string[] Tags(string[] keywords);

        [OperationContract]
        bool Insert(string[] keywords);

        [OperationContract]
        bool Delete(string[] keywords);
    }

    class MainService : IMainService
    {
        public string[] Select(string[] keywords)
        {
            ServiceCommonActions.LogAdvanced(GetClientIP(), "SELECT", keywords);

            return ServiceCommonActions.Select(keywords);
        }

        public string[] Tags(string[] keywords)
        {
            ServiceCommonActions.LogAdvanced(GetClientIP(), "TAGS", keywords);

            return ServiceCommonActions.Tags(keywords);
        }

        public bool Insert(string[] keywords)
        {
            ServiceCommonActions.LogAdvanced(GetClientIP(), "INSERT", keywords);

            return ServiceCommonActions.Insert(keywords);
        }

        public bool Delete(string[] keywords)
        {
            ServiceCommonActions.LogAdvanced(GetClientIP(), "DELETE", keywords);

            return ServiceCommonActions.Delete(keywords);
        }

        /// <summary>
        /// Функция возвращает IP-адрес клиента, выполняющего операцию
        /// службы (работает только в сетях TCP или HTTP)
        /// </summary>
        /// <returns>IP-адрес клиента</returns>

        private string GetClientIP()
        {
            OperationContext context = OperationContext.Current;
            MessageProperties messageProperties = context.IncomingMessageProperties;
            RemoteEndpointMessageProperty endpointProperty =
                messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;

            return endpointProperty.Address;
        }

        /// <summary>
        /// Функция устанавливает соединение со службой
        /// IMainService через TCP
        /// </summary>
        /// <returns>Соеденине с IMainService, null если удаленный хост не отвечает</returns>

        public static IMainService Connect()
        {
            EndpointAddress address = new EndpointAddress(Setup.ServiceMainAddress);
            NetTcpBinding binding = new NetTcpBinding();

            binding.Security.Mode = SecurityMode.None;

            try
            {
                ChannelFactory<IMainService> factory = new ChannelFactory<IMainService>(binding, address);
                return factory.CreateChannel();
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// Функция закрывает соединение со службой
        /// IMainService через TCP
        /// </summary>
        /// <param name="service">Соеденине с IMainService</param>

        public static void Disconnect(IMainService service)
        {
            ICommunicationObject channel = service as ICommunicationObject;

            if (service == null)
                return;

            channel.Close();
        }
    }
}
